package com.lxu;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * 针对VolatileDemo3进行锁操作，解决问题
 */
public class VolatileDemo4 {

    public static void main(String[] args) throws Exception {
        MyThread4 myThread = new MyThread4();
        List<Future> futureList = new ArrayList<Future>();
        ExecutorService pool = Executors.newFixedThreadPool(5);
        for (int i = 0; i < 100; i++) {
            futureList.add(pool.submit(myThread));
        }
        for (Future future : futureList) {
            future.get();
        }
        pool.shutdown();
        System.out.println("counter值为：" + myThread.getCounter());
    }
}

class MyThread4 implements Callable {

    private volatile int counter = 0;

    public int getCounter() {
        return counter;
    }

    @Override
    public Object call() throws Exception {
        synchronized (MyThread4.class) {
            for (int i = 0; i < 100; i++) {
                this.counter++;
            }
        }
        return "";
    }
}